import java.util.Stack;

/**
* @description: 1124. 表现良好的最长时间段
* @author hewei
* @date 2022/9/26 15:49
* @version 1.0
*/

public class LongestWPI {

    public static void main(String[] args) {
        int[] nums = {9,9,6,0,6,6,9};
        System.out.println(new LongestWPI().longestWPI(nums));
    }

    public int longestWPI(int[] hours) {
        int n = hours.length;
        int[] temp = new int[n + 1];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            sum += hours[i] > 8 ? 1 : -1;
            temp[i + 1] = sum;
        }
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        for (int i = 1; i < n + 1; i++) {
            if (temp[i] < temp[stack.peek()]) stack.push(i);
        }
        int ans = 0;
        for (int i = n; i >= 0; i--) {
            while (!stack.isEmpty() && temp[i] > temp[stack.peek()]) {
                Integer pop = stack.pop();
                ans = Math.max(ans, i - pop);
            }
        }
        return ans;
    }
}
